package com.hk.common.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 身份证工具类
 *
 */
public class PersonalIdUtils {
    /**
     * 身份证转成年龄
     *
     * */
    public static int ConversionAge(String personalId) throws Exception {
        personalId = personalId.substring(6,14);
        Date birthDay = new SimpleDateFormat("yyyyMMdd").parse(personalId);
        return getAge(birthDay);
    }


    /**
     * 获取病人岁数
     *
     * @param birthDay
     * @return age
     */
    public static int getAge(Date birthDay) {
        //身份证时间
        Calendar bef = Calendar.getInstance();
        //当前时间
        Calendar aft = Calendar.getInstance();
        Date now = DateUtils.getDateNoTime(new Date());
        aft.setTime(now);
        bef.setTime(birthDay);
        int age = aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR);
        // 设置成相同年 比较月份
        bef.set(Calendar.YEAR,aft.get(Calendar.YEAR));
        long sub = Math.abs(now.getTime() - birthDay.getTime());
        //大于0，则为当前年龄
        if (sub < 0) {
            age--;
        }
        return age;
    }


    public static void main(String[] args) {
        try {
            System.out.println(ConversionAge("342225199509234438"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
